home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1993 July / InfoMagic USENET CD-ROM July 1993.ISO / sources / unix / volume22 / gawk2.11 / part06 < prev    next >
Encoding:
Internet Message Format  |  1990-06-07  |  54.5 KB

  1. Subject:  v22i092:  GNU AWK, version 2.11, Part06/16
  2. Newsgroups: comp.sources.unix
  3. Approved: rsalz@uunet.UU.NET
  4. X-Checksum-Snefru: 6df48446 cf9bff47 23c8bae9 3bf959c3
  5.  
  6. Submitted-by: "Arnold D. Robbins" <arnold@unix.cc.emory.edu>
  7. Posting-number: Volume 22, Issue 92
  8. Archive-name: gawk2.11/part06
  9.  
  10. #! /bin/sh
  11. # This is a shell archive.  Remove anything before this line, then feed it
  12. # into a shell via "sh file" or similar.  To overwrite existing files,
  13. # type "sh file -c".
  14. # The tool that generated this appeared in the comp.sources.unix newsgroup;
  15. # send mail to comp-sources-unix@uunet.uu.net if you want that tool.
  16. # Contents:  ./gawk.texinfo.03 ./missing.d/strchr.c ./version.sh
  17. # Wrapped by rsalz@litchi.bbn.com on Wed Jun  6 12:24:50 1990
  18. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  19. echo If this archive is complete, you will see the following message:
  20. echo '          "shar: End of archive 6 (of 16)."'
  21. if test -f './gawk.texinfo.03' -a "${1}" != "-c" ; then 
  22.   echo shar: Will not clobber existing file \"'./gawk.texinfo.03'\"
  23. else
  24.   echo shar: Extracting \"'./gawk.texinfo.03'\" \(49625 characters\)
  25.   sed "s/^X//" >'./gawk.texinfo.03' <<'END_OF_FILE'
  26. X             printf format, "----", "------" @}
  27. X     @{ printf format, $1, $2 @}' BBS-list
  28. X@end example
  29. X
  30. XSee if you can use the @code{printf} statement to line up the headings and
  31. Xtable data for our @file{inventory-shipped} example covered earlier in the
  32. Xsection on the @code{print} statement (@pxref{Print}).
  33. X
  34. X@node Redirection, Special Files, Printf, Printing
  35. X@section Redirecting Output of @code{print} and @code{printf}
  36. X
  37. X@cindex output redirection
  38. X@cindex redirection of output
  39. XSo far we have been dealing only with output that prints to the standard
  40. Xoutput, usually your terminal.  Both @code{print} and @code{printf} can be
  41. Xtold to send their output to other places.  This is called
  42. X@dfn{redirection}.@refill
  43. X
  44. XA redirection appears after the @code{print} or @code{printf} statement.
  45. XRedirections in @code{awk} are written just like redirections in shell
  46. Xcommands, except that they are written inside the @code{awk} program.
  47. X
  48. X@menu
  49. X* File/Pipe Redirection::       Redirecting Output to Files and Pipes.
  50. X* Close Output::                How to close output files and pipes.
  51. X@end menu
  52. X
  53. X@node File/Pipe Redirection, Close Output, Redirection, Redirection
  54. X@subsection Redirecting Output to Files and Pipes
  55. X
  56. XHere are the three forms of output redirection.  They are all shown for
  57. Xthe @code{print} statement, but they work identically for @code{printf}
  58. Xalso.
  59. X
  60. X@table @code
  61. X@item print @var{items} > @var{output-file}
  62. XThis type of redirection prints the items onto the output file
  63. X@var{output-file}.  The file name @var{output-file} can be any
  64. Xexpression.  Its value is changed to a string and then used as a
  65. Xfile name (@pxref{Expressions}).@refill
  66. X
  67. XWhen this type of redirection is used, the @var{output-file} is erased
  68. Xbefore the first output is written to it.  Subsequent writes do not
  69. Xerase @var{output-file}, but append to it.  If @var{output-file} does
  70. Xnot exist, then it is created.@refill
  71. X
  72. XFor example, here is how one @code{awk} program can write a list of
  73. XBBS names to a file @file{name-list} and a list of phone numbers to a
  74. Xfile @file{phone-list}.  Each output file contains one name or number
  75. Xper line.
  76. X
  77. X@example
  78. Xawk '@{ print $2 > "phone-list"
  79. X       print $1 > "name-list" @}' BBS-list
  80. X@end example
  81. X
  82. X@item print @var{items} >> @var{output-file}
  83. XThis type of redirection prints the items onto the output file
  84. X@var{output-file}.  The difference between this and the
  85. Xsingle-@samp{>} redirection is that the old contents (if any) of
  86. X@var{output-file} are not erased.  Instead, the @code{awk} output is
  87. Xappended to the file.
  88. X
  89. X@cindex pipes for output
  90. X@cindex output, piping
  91. X@item print @var{items} | @var{command}
  92. XIt is also possible to send output through a @dfn{pipe} instead of into a
  93. Xfile.   This type of redirection opens a pipe to @var{command} and writes
  94. Xthe values of @var{items} through this pipe, to another process created
  95. Xto execute @var{command}.@refill
  96. X
  97. XThe redirection argument @var{command} is actually an @code{awk}
  98. Xexpression.  Its value is converted to a string, whose contents give the
  99. Xshell command to be run.
  100. X
  101. XFor example, this produces two files, one unsorted list of BBS names
  102. Xand one list sorted in reverse alphabetical order:
  103. X
  104. X@example
  105. Xawk '@{ print $1 > "names.unsorted"
  106. X       print $1 | "sort -r > names.sorted" @}' BBS-list
  107. X@end example
  108. X
  109. XHere the unsorted list is written with an ordinary redirection while
  110. Xthe sorted list is written by piping through the @code{sort} utility.
  111. X
  112. XHere is an example that uses redirection to mail a message to a mailing
  113. Xlist @samp{bug-system}.  This might be useful when trouble is encountered
  114. Xin an @code{awk} script run periodically for system maintenance.
  115. X
  116. X@example
  117. Xprint "Awk script failed:", $0 | "mail bug-system"
  118. Xprint "at record number", FNR, "of", FILENAME  | "mail bug-system"
  119. Xclose("mail bug-system")
  120. X@end example
  121. X
  122. XWe call the @code{close} function here because it's a good idea to close
  123. Xthe pipe as soon as all the intended output has been sent to it.
  124. X@xref{Close Output}, for more information on this.
  125. X@end table
  126. X
  127. XRedirecting output using @samp{>}, @samp{>>}, or @samp{|} asks the system
  128. Xto open a file or pipe only if the particular @var{file} or @var{command}
  129. Xyou've specified has not already been written to by your program.@refill
  130. X
  131. X@node Close Output, , File/Pipe Redirection, Redirection
  132. X@subsection Closing Output Files and Pipes
  133. X@cindex closing output files and pipes
  134. X@findex close
  135. X
  136. XWhen a file or pipe is opened, the file name or command associated with
  137. Xit is remembered by @code{awk} and subsequent writes to the same file or
  138. Xcommand are appended to the previous writes.  The file or pipe stays
  139. Xopen until @code{awk} exits.  This is usually convenient.
  140. X
  141. XSometimes there is a reason to close an output file or pipe earlier
  142. Xthan that.  To do this, use the @code{close} function, as follows:
  143. X
  144. X@example
  145. Xclose(@var{filename})
  146. X@end example
  147. X
  148. X@noindent
  149. Xor
  150. X
  151. X@example
  152. Xclose(@var{command})
  153. X@end example
  154. X
  155. XThe argument @var{filename} or @var{command} can be any expression.
  156. XIts value must exactly equal the string used to open the file or pipe
  157. Xto begin with---for example, if you open a pipe with this:
  158. X
  159. X@example
  160. Xprint $1 | "sort -r > names.sorted"
  161. X@end example
  162. X
  163. X@noindent
  164. Xthen you must close it with this:
  165. X
  166. X@example
  167. Xclose("sort -r > names.sorted")
  168. X@end example
  169. X
  170. XHere are some reasons why you might need to close an output file:
  171. X
  172. X@itemize @bullet
  173. X@item
  174. XTo write a file and read it back later on in the same @code{awk}
  175. Xprogram.  Close the file when you are finished writing it; then
  176. Xyou can start reading it with @code{getline} (@pxref{Getline}).
  177. X
  178. X@item
  179. XTo write numerous files, successively, in the same @code{awk}
  180. Xprogram.  If you don't close the files, eventually you will exceed the
  181. Xsystem limit on the number of open files in one process.  So close
  182. Xeach one when you are finished writing it.
  183. X
  184. X@item
  185. XTo make a command finish.  When you redirect output through a pipe,
  186. Xthe command reading the pipe normally continues to try to read input
  187. Xas long as the pipe is open.  Often this means the command cannot
  188. Xreally do its work until the pipe is closed.  For example, if you
  189. Xredirect output to the @code{mail} program, the message is not
  190. Xactually sent until the pipe is closed.
  191. X
  192. X@item
  193. XTo run the same program a second time, with the same arguments.
  194. XThis is not the same thing as giving more input to the first run!
  195. X
  196. XFor example, suppose you pipe output to the @code{mail} program.  If you
  197. Xoutput several lines redirected to this pipe without closing it, they make
  198. Xa single message of several lines.  By contrast, if you close the pipe
  199. Xafter each line of output, then each line makes a separate message.
  200. X@end itemize
  201. X
  202. X@node Special Files, , Redirection, Printing
  203. X@section Standard I/O Streams
  204. X@cindex standard input
  205. X@cindex standard output
  206. X@cindex standard error output
  207. X@cindex file descriptors
  208. X
  209. XRunning programs conventionally have three input and output streams
  210. Xalready available to them for reading and writing.  These are known as
  211. Xthe @dfn{standard input}, @dfn{standard output}, and @dfn{standard error
  212. Xoutput}.  These streams are, by default, terminal input and output, but
  213. Xthey are often redirected with the shell, via the @samp{<}, @samp{<<},
  214. X@samp{>}, @samp{>>}, @samp{>&} and @samp{|} operators.  Standard error
  215. Xis used only for writing error messages; the reason we have two separate
  216. Xstreams, standard output and standard error, is so that they can be
  217. Xredirected separately.
  218. X
  219. X@c @cindex differences between @code{gawk} and @code{awk}
  220. XIn other implementations of @code{awk}, the only way to write an error
  221. Xmessage to standard error in an @code{awk} program is as follows:
  222. X
  223. X@example
  224. Xprint "Serious error detected!\n" | "cat 1>&2"
  225. X@end example
  226. X
  227. X@noindent
  228. XThis works by opening a pipeline to a shell command which can access the
  229. Xstandard error stream which it inherits from the @code{awk} process.
  230. XThis is far from elegant, and is also inefficient, since it requires a
  231. Xseparate process.  So people writing @code{awk} programs have often
  232. Xneglected to do this.  Instead, they have sent the error messages to the
  233. Xterminal, like this:
  234. X
  235. X@example
  236. XNF != 4 @{
  237. X   printf("line %d skipped: doesn't have 4 fields\n", FNR) > "/dev/tty"
  238. X@}
  239. X@end example
  240. X
  241. X@noindent
  242. XThis has the same effect most of the time, but not always: although the
  243. Xstandard error stream is usually the terminal, it can be redirected, and
  244. Xwhen that happens, writing to the terminal is not correct.  In fact, if
  245. X@code{awk} is run from a background job, it may not have a terminal at all.
  246. XThen opening @file{/dev/tty} will fail.
  247. X
  248. X@code{gawk} provides special file names for accessing the three standard
  249. Xstreams.  When you redirect input or output in @code{gawk}, if the file name
  250. Xmatches one of these special names, then @code{gawk} directly uses the
  251. Xstream it stands for.
  252. X
  253. X@cindex @file{/dev/stdin}
  254. X@cindex @file{/dev/stdout}
  255. X@cindex @file{/dev/stderr}
  256. X@cindex @file{/dev/fd/}
  257. X@table @file
  258. X@item /dev/stdin
  259. XThe standard input (file descriptor 0).
  260. X
  261. X@item /dev/stdout
  262. XThe standard output (file descriptor 1).
  263. X
  264. X@item /dev/stderr
  265. XThe standard error output (file descriptor 2).
  266. X
  267. X@item /dev/fd/@var{n}
  268. XThe file associated with file descriptor @var{n}.  Such a file must have
  269. Xbeen opened by the program initiating the @code{awk} execution (typically
  270. Xthe shell).  Unless you take special pains, only descriptors 0, 1 and 2
  271. Xare available.
  272. X@end table
  273. X
  274. XThe file names @file{/dev/stdin}, @file{/dev/stdout}, and @file{/dev/stderr}
  275. Xare aliases for @file{/dev/fd/0}, @file{/dev/fd/1}, and @file{/dev/fd/2},
  276. Xrespectively, but they are more self-explanatory.
  277. X
  278. XThe proper way to write an error message in a @code{gawk} program
  279. Xis to use @file{/dev/stderr}, like this:
  280. X
  281. X@example
  282. XNF != 4 @{
  283. X  printf("line %d skipped: doesn't have 4 fields\n", FNR) > "/dev/stderr"
  284. X@}
  285. X@end example
  286. X
  287. XRecognition of these special file names is disabled if @code{gawk} is in
  288. Xcompatibility mode (@pxref{Command Line}).
  289. X
  290. X@node One-liners, Patterns, Printing, Top
  291. X@chapter Useful ``One-liners''
  292. X
  293. X@cindex one-liners
  294. XUseful @code{awk} programs are often short, just a line or two.  Here is a
  295. Xcollection of useful, short programs to get you started.  Some of these
  296. Xprograms contain constructs that haven't been covered yet.  The description
  297. Xof the program will give you a good idea of what is going on, but please
  298. Xread the rest of the manual to become an @code{awk} expert!
  299. X
  300. X@table @code
  301. X@item awk '@{ num_fields = num_fields + NF @}
  302. X@itemx @ @ @ @ @ END @{ print num_fields @}'
  303. XThis program prints the total number of fields in all input lines.
  304. X
  305. X@item awk 'length($0) > 80'
  306. XThis program prints every line longer than 80 characters.  The sole
  307. Xrule has a relational expression as its pattern, and has no action (so the
  308. Xdefault action, printing the record, is used).
  309. X
  310. X@item awk 'NF > 0'
  311. XThis program prints every line that has at least one field.  This is an
  312. Xeasy way to delete blank lines from a file (or rather, to create a new
  313. Xfile similar to the old file but from which the blank lines have been
  314. Xdeleted).
  315. X
  316. X@item awk '@{ if (NF > 0) print @}'
  317. XThis program also prints every line that has at least one field.  Here we
  318. Xallow the rule to match every line, then decide in the action whether
  319. Xto print.
  320. X
  321. X@item awk@ 'BEGIN@ @{@ for (i = 1; i <= 7; i++)
  322. X@itemx @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ print int(101 * rand()) @}'
  323. XThis program prints 7 random numbers from 0 to 100, inclusive.
  324. X
  325. X@item ls -l @var{files} | awk '@{ x += $4 @} ; END @{ print "total bytes: " x @}'
  326. XThis program prints the total number of bytes used by @var{files}.
  327. X
  328. X@item expand@ @var{file}@ |@ awk@ '@{ if (x < length()) x = length() @}
  329. X@itemx @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ END @{ print "maximum line length is " x @}'
  330. XThis program prints the maximum line length of @var{file}.  The input
  331. Xis piped through the @code{expand} program to change tabs into spaces,
  332. Xso the widths compared are actually the right-margin columns.
  333. X@end table
  334. X
  335. X@node Patterns, Actions, One-liners, Top
  336. X@chapter Patterns
  337. X@cindex pattern, definition of
  338. X
  339. XPatterns in @code{awk} control the execution of rules: a rule is
  340. Xexecuted when its pattern matches the current input record.  This
  341. Xchapter tells all about how to write patterns.
  342. X
  343. X@menu
  344. X* Kinds of Patterns::    A list of all kinds of patterns.
  345. X                         The following subsections describe them in detail.
  346. X
  347. X* Empty::                The empty pattern, which matches every record.
  348. X
  349. X* Regexp::               Regular expressions such as @samp{/foo/}.
  350. X
  351. X* Comparison Patterns::  Comparison expressions such as @code{$1 > 10}.
  352. X
  353. X* Boolean Patterns::     Combining comparison expressions.
  354. X
  355. X* Expression Patterns::  Any expression can be used as a pattern.
  356. X
  357. X* Ranges::               Using pairs of patterns to specify record ranges.
  358. X
  359. X* BEGIN/END::            Specifying initialization and cleanup rules.
  360. X@end menu
  361. X
  362. X@node Kinds of Patterns, Empty, Patterns, Patterns
  363. X@section Kinds of Patterns
  364. X@cindex patterns, types of
  365. X
  366. XHere is a summary of the types of patterns supported in @code{awk}.
  367. X
  368. X@table @code
  369. X@item /@var{regular expression}/
  370. XA regular expression as a pattern.  It matches when the text of the
  371. Xinput record fits the regular expression.  (@xref{Regexp, , Regular
  372. XExpressions as Patterns}.)
  373. X
  374. X@item @var{expression}
  375. XA single expression.  It matches when its value, converted to a number,
  376. Xis nonzero (if a number) or nonnull (if a string).  (@xref{Expression
  377. XPatterns}.)
  378. X
  379. X@item @var{pat1}, @var{pat2}
  380. XA pair of patterns separated by a comma, specifying a range of records.
  381. X(@xref{Ranges, , Specifying Record Ranges With Patterns}.)
  382. X
  383. X@item BEGIN
  384. X@itemx END
  385. XSpecial patterns to supply start-up or clean-up information to
  386. X@code{awk}.  (@xref{BEGIN/END}.)
  387. X
  388. X@item @var{null}
  389. XThe empty pattern matches every input record.  (@xref{Empty, , The Empty
  390. XPattern}.)
  391. X@end table
  392. X
  393. X@node Empty, Regexp, Kinds of Patterns, Patterns
  394. X@section The Empty Pattern
  395. X
  396. X@cindex empty pattern
  397. X@cindex pattern, empty
  398. XAn empty pattern is considered to match @emph{every} input record.  For
  399. Xexample, the program:@refill
  400. X
  401. X@example
  402. Xawk '@{ print $1 @}' BBS-list
  403. X@end example
  404. X
  405. X@noindent
  406. Xprints just the first field of every record.
  407. X
  408. X@node Regexp, Comparison Patterns, Empty, Patterns
  409. X@section Regular Expressions as Patterns
  410. X@cindex pattern, regular expressions
  411. X@cindex regexp
  412. X@cindex regular expressions as patterns
  413. X
  414. XA @dfn{regular expression}, or @dfn{regexp}, is a way of describing a
  415. Xclass of strings.  A regular expression enclosed in slashes (@samp{/})
  416. Xis an @code{awk} pattern that matches every input record whose text
  417. Xbelongs to that class.
  418. X
  419. XThe simplest regular expression is a sequence of letters, numbers, or
  420. Xboth.  Such a regexp matches any string that contains that sequence.
  421. XThus, the regexp @samp{foo} matches any string containing @samp{foo}.
  422. XTherefore, the pattern @code{/foo/} matches any input record containing
  423. X@samp{foo}.  Other kinds of regexps let you specify more complicated
  424. Xclasses of strings.
  425. X
  426. X@menu
  427. X* Usage: Regexp Usage.          How regexps are used in patterns.
  428. X* Operators: Regexp Operators.  How to write a regexp.
  429. X* Case-sensitivity::            How to do case-insensitive matching.
  430. X@end menu
  431. X
  432. X@node Regexp Usage, Regexp Operators, Regexp, Regexp
  433. X@subsection How to Use Regular Expressions
  434. X
  435. XA regular expression can be used as a pattern by enclosing it in
  436. Xslashes.  Then the regular expression is matched against the entire text
  437. Xof each record.  (Normally, it only needs to match some part of the text
  438. Xin order to succeed.)  For example, this prints the second field of each
  439. Xrecord that contains @samp{foo} anywhere:
  440. X
  441. X@example
  442. Xawk '/foo/ @{ print $2 @}' BBS-list
  443. X@end example
  444. X
  445. X@cindex regular expression matching operators
  446. X@cindex string-matching operators
  447. X@cindex operators, string-matching
  448. X@cindex operators, regular expression matching
  449. X@cindex regexp search operators
  450. XRegular expressions can also be used in comparison expressions.  Then
  451. Xyou can specify the string to match against; it need not be the entire
  452. Xcurrent input record.  These comparison expressions can be used as
  453. Xpatterns or in @code{if} and @code{while} statements.
  454. X
  455. X@table @code
  456. X@item @var{exp} ~ /@var{regexp}/
  457. XThis is true if the expression @var{exp} (taken as a character string)
  458. Xis matched by @var{regexp}.  The following example matches, or selects,
  459. Xall input records with the upper-case letter @samp{J} somewhere in the
  460. Xfirst field:@refill
  461. X
  462. X@example
  463. Xawk '$1 ~ /J/' inventory-shipped
  464. X@end example
  465. X
  466. XSo does this:
  467. X
  468. X@example
  469. Xawk '@{ if ($1 ~ /J/) print @}' inventory-shipped
  470. X@end example
  471. X
  472. X@item @var{exp} !~ /@var{regexp}/
  473. XThis is true if the expression @var{exp} (taken as a character string)
  474. Xis @emph{not} matched by @var{regexp}.  The following example matches,
  475. Xor selects, all input records whose first field @emph{does not} contain
  476. Xthe upper-case letter @samp{J}:@refill
  477. X
  478. X@example
  479. Xawk '$1 !~ /J/' inventory-shipped
  480. X@end example
  481. X@end table
  482. X
  483. X@cindex computed regular expressions
  484. X@cindex regular expressions, computed
  485. X@cindex dynamic regular expressions
  486. XThe right hand side of a @samp{~} or @samp{!~} operator need not be a
  487. Xconstant regexp (i.e., a string of characters between slashes).  It may
  488. Xbe any expression.  The expression is evaluated, and converted if
  489. Xnecessary to a string; the contents of the string are used as the
  490. Xregexp.  A regexp that is computed in this way is called a @dfn{dynamic
  491. Xregexp}.  For example:
  492. X
  493. X@example
  494. Xidentifier_regexp = "[A-Za-z_][A-Za-z_0-9]+"
  495. X$0 ~ identifier_regexp
  496. X@end example
  497. X
  498. X@noindent
  499. Xsets @code{identifier_regexp} to a regexp that describes @code{awk}
  500. Xvariable names, and tests if the input record matches this regexp.
  501. X
  502. X@node Regexp Operators, Case-sensitivity, Regexp Usage, Regexp
  503. X@subsection Regular Expression Operators
  504. X@cindex metacharacters
  505. X@cindex regular expression metacharacters
  506. X
  507. XYou can combine regular expressions with the following characters,
  508. Xcalled @dfn{regular expression operators}, or @dfn{metacharacters}, to
  509. Xincrease the power and versatility of regular expressions.
  510. X
  511. XHere is a table of metacharacters.  All characters not listed in the
  512. Xtable stand for themselves.
  513. X
  514. X@table @code
  515. X@item ^
  516. XThis matches the beginning of the string or the beginning of a line
  517. Xwithin the string.  For example:
  518. X
  519. X@example
  520. X^@@chapter
  521. X@end example
  522. X
  523. X@noindent
  524. Xmatches the @samp{@@chapter} at the beginning of a string, and can be used
  525. Xto identify chapter beginnings in Texinfo source files.
  526. X
  527. X@item $
  528. XThis is similar to @samp{^}, but it matches only at the end of a string
  529. Xor the end of a line within the string.  For example:
  530. X
  531. X@example
  532. Xp$
  533. X@end example
  534. X
  535. X@noindent
  536. Xmatches a record that ends with a @samp{p}.
  537. X
  538. X@item .
  539. XThis matches any single character except a newline.  For example:
  540. X
  541. X@example
  542. X.P
  543. X@end example
  544. X
  545. X@noindent
  546. Xmatches any single character followed by a @samp{P} in a string.  Using
  547. Xconcatenation we can make regular expressions like @samp{U.A}, which
  548. Xmatches any three-character sequence that begins with @samp{U} and ends
  549. Xwith @samp{A}.
  550. X
  551. X@item [@dots{}]
  552. XThis is called a @dfn{character set}.  It matches any one of the
  553. Xcharacters that are enclosed in the square brackets.  For example:
  554. X
  555. X@example
  556. X[MVX]
  557. X@end example
  558. X
  559. X@noindent
  560. Xmatches any of the characters @samp{M}, @samp{V}, or @samp{X} in a
  561. Xstring.@refill
  562. X
  563. XRanges of characters are indicated by using a hyphen between the beginning
  564. Xand ending characters, and enclosing the whole thing in brackets.  For
  565. Xexample:@refill
  566. X
  567. X@example
  568. X[0-9]
  569. X@end example
  570. X
  571. X@noindent
  572. Xmatches any digit.
  573. X
  574. XTo include the character @samp{\}, @samp{]}, @samp{-} or @samp{^} in a
  575. Xcharacter set, put a @samp{\} in front of it.  For example:
  576. X
  577. X@example
  578. X[d\]]
  579. X@end example
  580. X
  581. X@noindent
  582. Xmatches either @samp{]}, or @samp{d}.@refill
  583. X
  584. XThis treatment of @samp{\} is compatible with other @code{awk}
  585. Ximplementations but incompatible with the proposed POSIX specification
  586. Xfor @code{awk}.  The current draft specifies the use of the same syntax
  587. Xused in @code{egrep}.
  588. X
  589. XWe may change @code{gawk} to fit the standard, once we are sure it will
  590. Xno longer change.  For the meanwhile, the @samp{-a} option specifies the
  591. Xtraditional @code{awk} syntax described above (which is also the
  592. Xdefault), while the @samp{-e} option specifies @code{egrep} syntax.
  593. X@xref{Options}.
  594. X
  595. XIn @code{egrep} syntax, backslash is not syntactically special within
  596. Xsquare brackets.  This means that special tricks have to be used to
  597. Xrepresent the characters @samp{]}, @samp{-} and @samp{^} as members of a
  598. Xcharacter set.
  599. X
  600. XTo match @samp{-}, write it as @samp{---}, which is a range containing
  601. Xonly @samp{-}.  You may also give @samp{-} as the first or last
  602. Xcharacter in the set.  To match @samp{^}, put it anywhere except as the
  603. Xfirst character of a set.  To match a @samp{]}, make it the first
  604. Xcharacter in the set.  For example:
  605. X
  606. X@example
  607. X[]d^]
  608. X@end example
  609. X
  610. X@noindent
  611. Xmatches either @samp{]}, @samp{d} or @samp{^}.@refill
  612. X
  613. X@item [^ @dots{}]
  614. XThis is a @dfn{complemented character set}.  The first character after
  615. Xthe @samp{[} @emph{must} be a @samp{^}.  It matches any characters
  616. X@emph{except} those in the square brackets.  For example:
  617. X
  618. X@example
  619. X[^0-9]
  620. X@end example
  621. X
  622. X@noindent
  623. Xmatches any character that is not a digit.
  624. X
  625. X@item |
  626. XThis is the @dfn{alternation operator} and it is used to specify
  627. Xalternatives.  For example:
  628. X
  629. X@example
  630. X^P|[0-9]
  631. X@end example
  632. X
  633. X@noindent
  634. Xmatches any string that matches either @samp{^P} or @samp{[0-9]}.  This
  635. Xmeans it matches any string that contains a digit or starts with @samp{P}.
  636. X
  637. XThe alternation applies to the largest possible regexps on either side.
  638. X@item (@dots{})
  639. XParentheses are used for grouping in regular expressions as in
  640. Xarithmetic.  They can be used to concatenate regular expressions
  641. Xcontaining the alternation operator, @samp{|}.
  642. X
  643. X@item *
  644. XThis symbol means that the preceding regular expression is to be
  645. Xrepeated as many times as possible to find a match.  For example:
  646. X
  647. X@example
  648. Xph*
  649. X@end example
  650. X
  651. X@noindent
  652. Xapplies the @samp{*} symbol to the preceding @samp{h} and looks for matches
  653. Xto one @samp{p} followed by any number of @samp{h}s.  This will also match
  654. Xjust @samp{p} if no @samp{h}s are present.
  655. X
  656. XThe @samp{*} repeats the @emph{smallest} possible preceding expression.
  657. X(Use parentheses if you wish to repeat a larger expression.)  It finds
  658. Xas many repetitions as possible.  For example:
  659. X
  660. X@example
  661. Xawk '/\(c[ad][ad]*r x\)/ @{ print @}' sample
  662. X@end example
  663. X
  664. X@noindent
  665. Xprints every record in the input containing a string of the form
  666. X@samp{(car x)}, @samp{(cdr x)}, @samp{(cadr x)}, and so on.@refill
  667. X
  668. X@item +
  669. XThis symbol is similar to @samp{*}, but the preceding expression must be
  670. Xmatched at least once.  This means that:
  671. X
  672. X@example
  673. Xwh+y
  674. X@end example
  675. X
  676. X@noindent
  677. Xwould match @samp{why} and @samp{whhy} but not @samp{wy}, whereas
  678. X@samp{wh*y} would match all three of these strings.  This is a simpler
  679. Xway of writing the last @samp{*} example:
  680. X
  681. X@example
  682. Xawk '/\(c[ad]+r x\)/ @{ print @}' sample
  683. X@end example
  684. X
  685. X@item ?
  686. XThis symbol is similar to @samp{*}, but the preceding expression can be
  687. Xmatched once or not at all.  For example:
  688. X
  689. X@example
  690. Xfe?d
  691. X@end example
  692. X
  693. X@noindent
  694. Xwill match @samp{fed} or @samp{fd}, but nothing else.@refill
  695. X
  696. X@item \
  697. XThis is used to suppress the special meaning of a character when
  698. Xmatching.  For example:
  699. X
  700. X@example
  701. X\$
  702. X@end example
  703. X
  704. X@noindent
  705. Xmatches the character @samp{$}.
  706. X
  707. XThe escape sequences used for string constants (@pxref{Constants}) are
  708. Xvalid in regular expressions as well; they are also introduced by a
  709. X@samp{\}.
  710. X@end table
  711. X
  712. XIn regular expressions, the @samp{*}, @samp{+}, and @samp{?} operators have
  713. Xthe highest precedence, followed by concatenation, and finally by @samp{|}.
  714. XAs in arithmetic, parentheses can change how operators are grouped.@refill
  715. X
  716. X@node Case-sensitivity,, Regexp Operators, Regexp
  717. X@subsection Case-sensitivity in Matching
  718. X
  719. XCase is normally significant in regular expressions, both when matching
  720. Xordinary characters (i.e., not metacharacters), and inside character
  721. Xsets.  Thus a @samp{w} in a regular expression matches only a lower case
  722. X@samp{w} and not an upper case @samp{W}.
  723. X
  724. XThe simplest way to do a case-independent match is to use a character
  725. Xset: @samp{[Ww]}.  However, this can be cumbersome if you need to use it
  726. Xoften; and it can make the regular expressions harder for humans to
  727. Xread.  There are two other alternatives that you might prefer.
  728. X
  729. XOne way to do a case-insensitive match at a particular point in the
  730. Xprogram is to convert the data to a single case, using the
  731. X@code{tolower} or @code{toupper} built-in string functions (which we
  732. Xhaven't discussed yet; @pxref{String Functions}).  For example:
  733. X
  734. X@example
  735. Xtolower($1) ~ /foo/  @{ @dots{} @}
  736. X@end example
  737. X
  738. X@noindent
  739. Xconverts the first field to lower case before matching against it.
  740. X
  741. XAnother method is to set the variable @code{IGNORECASE} to a nonzero
  742. Xvalue (@pxref{Built-in Variables}).  When @code{IGNORECASE} is not zero,
  743. X@emph{all} regexp operations ignore case.  Changing the value of
  744. X@code{IGNORECASE} dynamically controls the case sensitivity of your
  745. Xprogram as it runs.  Case is significant by default because
  746. X@code{IGNORECASE} (like most variables) is initialized to zero.
  747. X
  748. X@example
  749. Xx = "aB"
  750. Xif (x ~ /ab/) @dots{}   # this test will fail
  751. X
  752. XIGNORECASE = 1
  753. Xif (x ~ /ab/) @dots{}   # now it will succeed
  754. X@end example
  755. X
  756. XYou cannot generally use @code{IGNORECASE} to make certain rules
  757. Xcase-insensitive and other rules case-sensitive, because there is no way
  758. Xto set @code{IGNORECASE} just for the pattern of a particular rule.  To
  759. Xdo this, you must use character sets or @code{tolower}.  However, one
  760. Xthing you can do only with @code{IGNORECASE} is turn case-sensitivity on
  761. Xor off dynamically for all the rules at once.
  762. X
  763. X@code{IGNORECASE} can be set on the command line, or in a @code{BEGIN}
  764. Xrule.  Setting @code{IGNORECASE} from the command line is a way to make
  765. Xa program case-insensitive without having to edit it.
  766. X
  767. XThe value of @code{IGNORECASE} has no effect if @code{gawk} is in
  768. Xcompatibility mode (@pxref{Command Line}).  Case is always significant
  769. Xin compatibility mode.
  770. X
  771. X@node Comparison Patterns, Boolean Patterns, Regexp, Patterns
  772. X@section Comparison Expressions as Patterns
  773. X@cindex comparison expressions as patterns
  774. X@cindex pattern, comparison expressions
  775. X@cindex relational operators
  776. X@cindex operators, relational
  777. X
  778. X@dfn{Comparison patterns} test relationships such as equality between
  779. Xtwo strings or numbers.  They are a special case of expression patterns
  780. X(@pxref{Expression Patterns}).  They are written with @dfn{relational
  781. Xoperators}, which are a superset of those in C.  Here is a table of
  782. Xthem:
  783. X
  784. X@table @code
  785. X@item @var{x} < @var{y}
  786. XTrue if @var{x} is less than @var{y}.
  787. X
  788. X@item @var{x} <= @var{y}
  789. XTrue if @var{x} is less than or equal to @var{y}.
  790. X
  791. X@item @var{x} > @var{y}
  792. XTrue if @var{x} is greater than @var{y}.
  793. X
  794. X@item @var{x} >= @var{y}
  795. XTrue if @var{x} is greater than or equal to @var{y}.
  796. X
  797. X@item @var{x} == @var{y}
  798. XTrue if @var{x} is equal to @var{y}.
  799. X
  800. X@item @var{x} != @var{y}
  801. XTrue if @var{x} is not equal to @var{y}.
  802. X
  803. X@item @var{x} ~ @var{y}
  804. XTrue if @var{x} matches the regular expression described by @var{y}.
  805. X
  806. X@item @var{x} !~ @var{y}
  807. XTrue if @var{x} does not match the regular expression described by @var{y}.
  808. X@end table
  809. X
  810. XThe operands of a relational operator are compared as numbers if they
  811. Xare both numbers.  Otherwise they are converted to, and compared as,
  812. Xstrings (@pxref{Conversion}).  Strings are compared by comparing the
  813. Xfirst character of each, then the second character of each, and so on,
  814. Xuntil there is a difference.  If the two strings are equal until the
  815. Xshorter one runs out, the shorter one is considered to be less than the
  816. Xlonger one.  Thus, @code{"10"} is less than @code{"9"}.
  817. X
  818. XThe left operand of the @samp{~} and @samp{!~} operators is a string.
  819. XThe right operand is either a constant regular expression enclosed in
  820. Xslashes (@code{/@var{regexp}/}), or any expression, whose string value
  821. Xis used as a dynamic regular expression (@pxref{Regexp Usage}).
  822. X
  823. XThe following example prints the second field of each input record
  824. Xwhose first field is precisely @samp{foo}.
  825. X
  826. X@example
  827. Xawk '$1 == "foo" @{ print $2 @}' BBS-list
  828. X@end example
  829. X
  830. X@noindent
  831. XContrast this with the following regular expression match, which would
  832. Xaccept any record with a first field that contains @samp{foo}:
  833. X
  834. X@example
  835. Xawk '$1 ~ "foo" @{ print $2 @}' BBS-list
  836. X@end example
  837. X
  838. X@noindent
  839. Xor, equivalently, this one:
  840. X
  841. X@example
  842. Xawk '$1 ~ /foo/ @{ print $2 @}' BBS-list
  843. X@end example
  844. X
  845. X@node Boolean Patterns, Expression Patterns, Comparison Patterns, Patterns
  846. X@section Boolean Operators and Patterns
  847. X@cindex patterns, boolean
  848. X@cindex boolean patterns
  849. X
  850. XA @dfn{boolean pattern} is an expression which combines other patterns
  851. Xusing the @dfn{boolean operators} ``or'' (@samp{||}), ``and''
  852. X(@samp{&&}), and ``not'' (@samp{!}).  Whether the boolean pattern
  853. Xmatches an input record depends on whether its subpatterns match.
  854. X
  855. XFor example, the following command prints all records in the input file
  856. X@file{BBS-list} that contain both @samp{2400} and @samp{foo}.@refill
  857. X
  858. X@example
  859. Xawk '/2400/ && /foo/' BBS-list
  860. X@end example
  861. X
  862. XThe following command prints all records in the input file
  863. X@file{BBS-list} that contain @emph{either} @samp{2400} or @samp{foo}, or
  864. Xboth.@refill
  865. X
  866. X@example
  867. Xawk '/2400/ || /foo/' BBS-list
  868. X@end example
  869. X
  870. XThe following command prints all records in the input file
  871. X@file{BBS-list} that do @emph{not} contain the string @samp{foo}.
  872. X
  873. X@example
  874. Xawk '! /foo/' BBS-list
  875. X@end example
  876. X
  877. XNote that boolean patterns are a special case of expression patterns
  878. X(@pxref{Expression Patterns}); they are expressions that use the boolean
  879. Xoperators.  For complete information on the boolean operators, see
  880. X@ref{Boolean Ops}.
  881. X
  882. XThe subpatterns of a boolean pattern can be constant regular
  883. Xexpressions, comparisons, or any other @code{gawk} expressions.  Range
  884. Xpatterns are not expressions, so they cannot appear inside boolean
  885. Xpatterns.  Likewise, the special patterns @code{BEGIN} and @code{END},
  886. Xwhich never match any input record, are not expressions and cannot
  887. Xappear inside boolean patterns.
  888. X
  889. X@node Expression Patterns, Ranges, Boolean Patterns, Patterns
  890. X@section Expressions as Patterns
  891. X
  892. XAny @code{awk} expression is valid also as a pattern in @code{gawk}.
  893. XThen the pattern ``matches'' if the expression's value is nonzero (if a
  894. Xnumber) or nonnull (if a string).
  895. X
  896. XThe expression is reevaluated each time the rule is tested against a new
  897. Xinput record.  If the expression uses fields such as @code{$1}, the
  898. Xvalue depends directly on the new input record's text; otherwise, it
  899. Xdepends only on what has happened so far in the execution of the
  900. X@code{awk} program, but that may still be useful.
  901. X
  902. XComparison patterns are actually a special case of this.  For
  903. Xexample, the expression @code{$5 == "foo"} has the value 1 when the
  904. Xvalue of @code{$5} equals @code{"foo"}, and 0 otherwise; therefore, this
  905. Xexpression as a pattern matches when the two values are equal.
  906. X
  907. XBoolean patterns are also special cases of expression patterns.
  908. X
  909. XA constant regexp as a pattern is also a special case of an expression
  910. Xpattern.  @code{/foo/} as an expression has the value 1 if @samp{foo}
  911. Xappears in the current input record; thus, as a pattern, @code{/foo/}
  912. Xmatches any record containing @samp{foo}.
  913. X
  914. XOther implementations of @code{awk} are less general than @code{gawk}:
  915. Xthey allow comparison expressions, and boolean combinations thereof
  916. X(optionally with parentheses), but not necessarily other kinds of
  917. Xexpressions.
  918. X
  919. X@node Ranges, BEGIN/END, Expression Patterns, Patterns
  920. X@section Specifying Record Ranges With Patterns
  921. X
  922. X@cindex range pattern
  923. X@cindex patterns, range
  924. XA @dfn{range pattern} is made of two patterns separated by a comma, of
  925. Xthe form @code{@var{begpat}, @var{endpat}}.  It matches ranges of
  926. Xconsecutive input records.  The first pattern @var{begpat} controls
  927. Xwhere the range begins, and the second one @var{endpat} controls where
  928. Xit ends.  For example,@refill
  929. X
  930. X@example
  931. Xawk '$1 == "on", $1 == "off"'
  932. X@end example
  933. X
  934. X@noindent
  935. Xprints every record between @samp{on}/@samp{off} pairs, inclusive.
  936. X
  937. XIn more detail, a range pattern starts out by matching @var{begpat}
  938. Xagainst every input record; when a record matches @var{begpat}, the
  939. Xrange pattern becomes @dfn{turned on}.  The range pattern matches this
  940. Xrecord.  As long as it stays turned on, it automatically matches every
  941. Xinput record read.  But meanwhile, it also matches @var{endpat} against
  942. Xevery input record, and when that succeeds, the range pattern is turned
  943. Xoff again for the following record.  Now it goes back to checking
  944. X@var{begpat} against each record.
  945. X
  946. XThe record that turns on the range pattern and the one that turns it
  947. Xoff both match the range pattern.  If you don't want to operate on
  948. Xthese records, you can write @code{if} statements in the rule's action
  949. Xto distinguish them.
  950. X
  951. XIt is possible for a pattern to be turned both on and off by the same
  952. Xrecord, if both conditions are satisfied by that record.  Then the action is
  953. Xexecuted for just that record.
  954. X
  955. X@node BEGIN/END,, Ranges, Patterns
  956. X@section @code{BEGIN} and @code{END} Special Patterns
  957. X
  958. X@cindex @code{BEGIN} special pattern
  959. X@cindex patterns, @code{BEGIN}
  960. X@cindex @code{END} special pattern
  961. X@cindex patterns, @code{END}
  962. X@code{BEGIN} and @code{END} are special patterns.  They are not used to
  963. Xmatch input records.  Rather, they are used for supplying start-up or
  964. Xclean-up information to your @code{awk} script.  A @code{BEGIN} rule is
  965. Xexecuted, once, before the first input record has been read.  An @code{END}
  966. Xrule is executed, once, after all the input has been read.  For
  967. Xexample:@refill
  968. X
  969. X@group
  970. X@example
  971. Xawk 'BEGIN @{ print "Analysis of `foo'" @}
  972. X     /foo/ @{ ++foobar @}
  973. X     END   @{ print "`foo' appears " foobar " times." @}' BBS-list
  974. X@end example
  975. X@end group
  976. X
  977. XThis program finds out how many times the string @samp{foo} appears in
  978. Xthe input file @file{BBS-list}.  The @code{BEGIN} rule prints a title
  979. Xfor the report.  There is no need to use the @code{BEGIN} rule to
  980. Xinitialize the counter @code{foobar} to zero, as @code{awk} does this
  981. Xfor us automatically (@pxref{Variables}).
  982. X
  983. XThe second rule increments the variable @code{foobar} every time a
  984. Xrecord containing the pattern @samp{foo} is read.  The @code{END} rule
  985. Xprints the value of @code{foobar} at the end of the run.@refill
  986. X
  987. XThe special patterns @code{BEGIN} and @code{END} cannot be used in ranges
  988. Xor with boolean operators.
  989. X
  990. XAn @code{awk} program may have multiple @code{BEGIN} and/or @code{END}
  991. Xrules.  They are executed in the order they appear, all the @code{BEGIN}
  992. Xrules at start-up and all the @code{END} rules at termination.
  993. X
  994. XMultiple @code{BEGIN} and @code{END} sections are useful for writing
  995. Xlibrary functions, since each library can have its own @code{BEGIN} or
  996. X@code{END} rule to do its own initialization and/or cleanup.  Note that
  997. Xthe order in which library functions are named on the command line
  998. Xcontrols the order in which their @code{BEGIN} and @code{END} rules are
  999. Xexecuted.  Therefore you have to be careful to write such rules in
  1000. Xlibrary files so that it doesn't matter what order they are executed in.
  1001. X@xref{Command Line}, for more information on using library functions.
  1002. X
  1003. XIf an @code{awk} program only has a @code{BEGIN} rule, and no other
  1004. Xrules, then the program exits after the @code{BEGIN} rule has been run.
  1005. X(Older versions of @code{awk} used to keep reading and ignoring input
  1006. Xuntil end of file was seen.)  However, if an @code{END} rule exists as
  1007. Xwell, then the input will be read, even if there are no other rules in
  1008. Xthe program.  This is necessary in case the @code{END} rule checks the
  1009. X@code{NR} variable.
  1010. X
  1011. X@code{BEGIN} and @code{END} rules must have actions; there is no default
  1012. Xaction for these rules since there is no current record when they run.
  1013. X
  1014. X@node Actions, Expressions, Patterns, Top
  1015. X@chapter Actions: Overview
  1016. X@cindex action, definition of
  1017. X@cindex curly braces
  1018. X@cindex action, curly braces
  1019. X@cindex action, separating statements
  1020. X
  1021. XAn @code{awk} @dfn{program} or @dfn{script} consists of a series of
  1022. X@dfn{rules} and function definitions, interspersed.  (Functions are
  1023. Xdescribed later; see @ref{User-defined}.)
  1024. X
  1025. XA rule contains a pattern and an @dfn{action}, either of which may be
  1026. Xomitted.  The purpose of the action is to tell @code{awk} what to do
  1027. Xonce a match for the pattern is found.  Thus, the entire program
  1028. Xlooks somewhat like this:
  1029. X
  1030. X@example
  1031. X@r{[}@var{pattern}@r{]} @r{[}@{ @var{action} @}@r{]}
  1032. X@r{[}@var{pattern}@r{]} @r{[}@{ @var{action} @}@r{]}
  1033. X@dots{}
  1034. Xfunction @var{name} (@var{args}) @{ @dots{} @}
  1035. X@dots{}
  1036. X@end example
  1037. X
  1038. XAn action consists of one or more @code{awk} @dfn{statements}, enclosed
  1039. Xin curly braces (@samp{@{} and @samp{@}}).  Each statement specifies one
  1040. Xthing to be done.  The statements are separated by newlines or
  1041. Xsemicolons.
  1042. X
  1043. XThe curly braces around an action must be used even if the action
  1044. Xcontains only one statement, or even if it contains no statements at
  1045. Xall.  However, if you omit the action entirely, omit the curly braces as
  1046. Xwell.  (An omitted action is equivalent to @samp{@{ print $0 @}}.)
  1047. X
  1048. XHere are the kinds of statement supported in @code{awk}:
  1049. X
  1050. X@itemize @bullet
  1051. X@item
  1052. XExpressions, which can call functions or assign values to variables
  1053. X(@pxref{Expressions}).  Executing this kind of statement simply computes
  1054. Xthe value of the expression and then ignores it.  This is useful when
  1055. Xthe expression has side effects (@pxref{Assignment Ops}).
  1056. X
  1057. X@item
  1058. XControl statements, which specify the control flow of @code{awk}
  1059. Xprograms.  The @code{awk} language gives you C-like constructs
  1060. X(@code{if}, @code{for}, @code{while}, and so on) as well as a few
  1061. Xspecial ones (@pxref{Statements}).@refill
  1062. X
  1063. X@item
  1064. XCompound statements, which consist of one or more statements enclosed in
  1065. Xcurly braces.  A compound statement is used in order to put several
  1066. Xstatements together in the body of an @code{if}, @code{while}, @code{do}
  1067. Xor @code{for} statement.
  1068. X
  1069. X@item
  1070. XInput control, using the @code{getline} function (@pxref{Getline}),
  1071. Xand the @code{next} statement (@pxref{Next Statement}).
  1072. X
  1073. X@item
  1074. XOutput statements, @code{print} and @code{printf}.  @xref{Printing}.
  1075. X
  1076. X@item
  1077. XDeletion statements, for deleting array elements.  @xref{Delete}.
  1078. X@end itemize
  1079. X
  1080. X@iftex
  1081. XThe next two chapters cover in detail expressions and control
  1082. Xstatements, respectively.  We go on to treat arrays, and built-in
  1083. Xfunctions, both of which are used in expressions.  Then we proceed
  1084. Xto discuss how to define your own functions.
  1085. X@end iftex
  1086. X
  1087. X@node Expressions, Statements, Actions, Top
  1088. X@chapter Actions: Expressions
  1089. X@cindex expression
  1090. X
  1091. XExpressions are the basic building block of @code{awk} actions.  An
  1092. Xexpression evaluates to a value, which you can print, test, store in a
  1093. Xvariable or pass to a function.
  1094. X
  1095. XBut, beyond that, an expression can assign a new value to a variable
  1096. Xor a field, with an assignment operator.
  1097. X
  1098. XAn expression can serve as a statement on its own.  Most other kinds of
  1099. Xstatement contain one or more expressions which specify data to be
  1100. Xoperated on.  As in other languages, expressions in @code{awk} include
  1101. Xvariables, array references, constants, and function calls, as well as
  1102. Xcombinations of these with various operators.
  1103. X
  1104. X@menu
  1105. X* Constants::       String, numeric, and regexp constants.
  1106. X* Variables::       Variables give names to values for later use.
  1107. X* Arithmetic Ops::  Arithmetic operations (@samp{+}, @samp{-}, etc.)
  1108. X* Concatenation::   Concatenating strings.
  1109. X* Comparison Ops::  Comparison of numbers and strings with @samp{<}, etc.
  1110. X* Boolean Ops::     Combining comparison expressions using boolean operators
  1111. X                    @samp{||} (``or''), @samp{&&} (``and'') and @samp{!} (``not'').
  1112. X
  1113. X* Assignment Ops::  Changing the value of a variable or a field.
  1114. X* Increment Ops::   Incrementing the numeric value of a variable.
  1115. X
  1116. X* Conversion::      The conversion of strings to numbers and vice versa.
  1117. X* Conditional Exp:: Conditional expressions select between two subexpressions
  1118. X                    under control of a third subexpression.
  1119. X* Function Calls::  A function call is an expression.
  1120. X* Precedence::      How various operators nest.
  1121. X@end menu
  1122. X
  1123. X@node Constants, Variables, Expressions, Expressions
  1124. X@section Constant Expressions
  1125. X@cindex constants, types of
  1126. X@cindex string constants
  1127. X
  1128. XThe simplest type of expression is the @dfn{constant}, which always has
  1129. Xthe same value.  There are three types of constant: numeric constants,
  1130. Xstring constants, and regular expression constants.
  1131. X
  1132. X@cindex numeric constant
  1133. X@cindex numeric value
  1134. XA @dfn{numeric constant} stands for a number.  This number can be an
  1135. Xinteger, a decimal fraction, or a number in scientific (exponential)
  1136. Xnotation.  Note that all numeric values are represented within
  1137. X@code{awk} in double-precision floating point.  Here are some examples
  1138. Xof numeric constants, which all have the same value:
  1139. X
  1140. X@example
  1141. X105
  1142. X1.05e+2
  1143. X1050e-1
  1144. X@end example
  1145. X
  1146. XA string constant consists of a sequence of characters enclosed in
  1147. Xdouble-quote marks.  For example:
  1148. X
  1149. X@example
  1150. X"parrot"
  1151. X@end example
  1152. X
  1153. X@noindent
  1154. X@c @cindex differences between @code{gawk} and @code{awk}
  1155. Xrepresents the string whose contents are @samp{parrot}.  Strings in
  1156. X@code{gawk} can be of any length and they can contain all the possible
  1157. X8-bit ASCII characters including ASCII NUL.  Other @code{awk}
  1158. Ximplementations may have difficulty with some character codes.@refill
  1159. X
  1160. X@cindex escape sequence notation
  1161. XSome characters cannot be included literally in a string constant.  You
  1162. Xrepresent them instead with @dfn{escape sequences}, which are character
  1163. Xsequences beginning with a backslash (@samp{\}).
  1164. X
  1165. XOne use of an escape sequence is to include a double-quote character in
  1166. Xa string constant.  Since a plain double-quote would end the string, you
  1167. Xmust use @samp{\"} to represent a single double-quote character as a
  1168. Xpart of the string.  Backslash itself is another character that can't be
  1169. Xincluded normally; you write @samp{\\} to put one backslash in the
  1170. Xstring.  Thus, the string whose contents are the two characters
  1171. X@samp{"\} must be written @code{"\"\\"}.
  1172. X
  1173. XAnother use of backslash is to represent unprintable characters
  1174. Xsuch as newline.  While there is nothing to stop you from writing most
  1175. Xof these characters directly in a string constant, they may look ugly.
  1176. X
  1177. XHere is a table of all the escape sequences used in @code{awk}:
  1178. X
  1179. X@table @code
  1180. X@item \\
  1181. XRepresents a literal backslash, @samp{\}.
  1182. X
  1183. X@item \a
  1184. XRepresents the ``alert'' character, control-g, ASCII code 7.
  1185. X
  1186. X@item \b
  1187. XRepresents a backspace, control-h, ASCII code 8.
  1188. X
  1189. X@item \f
  1190. XRepresents a formfeed, control-l, ASCII code 12.
  1191. X
  1192. X@item \n
  1193. XRepresents a newline, control-j, ASCII code 10.
  1194. X
  1195. X@item \r
  1196. XRepresents a carriage return, control-m, ASCII code 13.
  1197. X
  1198. X@item \t
  1199. XRepresents a horizontal tab, control-i, ASCII code 9.
  1200. X
  1201. X@item \v
  1202. XRepresents a vertical tab, control-k, ASCII code 11.
  1203. X
  1204. X@item \@var{nnn}
  1205. XRepresents the octal value @var{nnn}, where @var{nnn} are one to three
  1206. Xdigits between 0 and 7.  For example, the code for the ASCII ESC
  1207. X(escape) character is @samp{\033}.@refill
  1208. X
  1209. X@item \x@var{hh@dots{}}
  1210. XRepresents the hexadecimal value @var{hh}, where @var{hh} are hexadecimal
  1211. Xdigits (@samp{0} through @samp{9} and either @samp{A} through @samp{F} or
  1212. X@samp{a} through @samp{f}).  Like the same construct in ANSI C, the escape
  1213. Xsequence continues until the first non-hexadecimal digit is seen.  However,
  1214. Xusing more than two hexadecimal digits produces undefined results.@refill
  1215. X@end table
  1216. X
  1217. XA constant regexp is a regular expression description enclosed in
  1218. Xslashes, such as @code{/^beginning and end$/}.  Most regexps used in
  1219. X@code{awk} programs are constant, but the @samp{~} and @samp{!~}
  1220. Xoperators can also match computed or ``dynamic'' regexps (@pxref{Regexp
  1221. XUsage}).
  1222. X
  1223. XConstant regexps are useful only with the @samp{~} and @samp{!~} operators;
  1224. Xyou cannot assign them to variables or print them.  They are not truly
  1225. Xexpressions in the usual sense.
  1226. X
  1227. X@node Variables, Arithmetic Ops, Constants, Expressions
  1228. X@section Variables
  1229. X@cindex variables, user-defined
  1230. X@cindex user-defined variables
  1231. X
  1232. XVariables let you give names to values and refer to them later.  You have
  1233. Xalready seen variables in many of the examples.  The name of a variable
  1234. Xmust be a sequence of letters, digits and underscores, but it may not begin
  1235. Xwith a digit.  Case is significant in variable names; @code{a} and @code{A}
  1236. Xare distinct variables.
  1237. X
  1238. XA variable name is a valid expression by itself; it represents the
  1239. Xvariable's current value.  Variables are given new values with
  1240. X@dfn{assignment operators} and @dfn{increment operators}.
  1241. X@xref{Assignment Ops}.
  1242. X
  1243. XA few variables have special built-in meanings, such as @code{FS}, the
  1244. Xfield separator, and @code{NF}, the number of fields in the current
  1245. Xinput record.  @xref{Built-in Variables}, for a list of them.  These
  1246. Xbuilt-in variables can be used and assigned just like all other
  1247. Xvariables, but their values are also used or changed automatically by
  1248. X@code{awk}.  Each built-in variable's name is made entirely of upper case
  1249. Xletters.
  1250. X
  1251. XVariables in @code{awk} can be assigned either numeric values or string
  1252. Xvalues.  By default, variables are initialized to the null string, which
  1253. Xis effectively zero if converted to a number.  So there is no need to
  1254. X``initialize'' each variable explicitly in @code{awk}, the way you would
  1255. Xneed to do in C or most other traditional programming languages.
  1256. X
  1257. X@menu
  1258. X* Assignment Options::  Setting variables on the command line and a summary
  1259. X                        of command line syntax.  This is an advanced method
  1260. X                        of input.
  1261. X@end menu
  1262. X
  1263. X@node Assignment Options,, Variables, Variables
  1264. X@subsection Assigning Variables on the Command Line
  1265. X
  1266. XYou can set any @code{awk} variable by including a @dfn{variable assignment}
  1267. Xamong the arguments on the command line when you invoke @code{awk}
  1268. X(@pxref{Command Line}).  Such an assignment has this form:
  1269. X
  1270. X@example
  1271. X@var{variable}=@var{text}
  1272. X@end example
  1273. X
  1274. X@noindent
  1275. XWith it, you can set a variable either at the beginning of the
  1276. X@code{awk} run or in between input files.
  1277. X
  1278. XIf you precede the assignment with the @samp{-v} option, like this:
  1279. X
  1280. X@example
  1281. X-v @var{variable}=@var{text}
  1282. X@end example
  1283. X
  1284. X@noindent
  1285. Xthen the variable is set at the very beginning, before even the
  1286. X@code{BEGIN} rules are run.  The @samp{-v} option and its assignment
  1287. Xmust precede all the file name arguments.
  1288. X
  1289. XOtherwise, the variable assignment is performed at a time determined by
  1290. Xits position among the input file arguments: after the processing of the
  1291. Xpreceding input file argument.  For example:
  1292. X
  1293. X@example
  1294. Xawk '@{ print $n @}' n=4 inventory-shipped n=2 BBS-list
  1295. X@end example
  1296. X
  1297. X@noindent
  1298. Xprints the value of field number @code{n} for all input records.  Before
  1299. Xthe first file is read, the command line sets the variable @code{n}
  1300. Xequal to 4.  This causes the fourth field to be printed in lines from
  1301. Xthe file @file{inventory-shipped}.  After the first file has finished,
  1302. Xbut before the second file is started, @code{n} is set to 2, so that the
  1303. Xsecond field is printed in lines from @file{BBS-list}.
  1304. X
  1305. XCommand line arguments are made available for explicit examination by
  1306. Xthe @code{awk} program in an array named @code{ARGV} (@pxref{Built-in
  1307. XVariables}).
  1308. X
  1309. X@node Arithmetic Ops, Concatenation, Variables, Expressions
  1310. X@section Arithmetic Operators
  1311. X@cindex arithmetic operators
  1312. X@cindex operators, arithmetic
  1313. X@cindex addition
  1314. X@cindex subtraction
  1315. X@cindex multiplication
  1316. X@cindex division
  1317. X@cindex remainder
  1318. X@cindex quotient
  1319. X@cindex exponentiation
  1320. X
  1321. XThe @code{awk} language uses the common arithmetic operators when
  1322. Xevaluating expressions.  All of these arithmetic operators follow normal
  1323. Xprecedence rules, and work as you would expect them to.  This example
  1324. Xdivides field three by field four, adds field two, stores the result
  1325. Xinto field one, and prints the resulting altered input record:
  1326. X
  1327. X@example
  1328. Xawk '@{ $1 = $2 + $3 / $4; print @}' inventory-shipped
  1329. X@end example
  1330. X
  1331. XThe arithmetic operators in @code{awk} are:
  1332. X
  1333. X@table @code
  1334. X@item @var{x} + @var{y}
  1335. XAddition.
  1336. X
  1337. X@item @var{x} - @var{y}
  1338. XSubtraction.
  1339. X
  1340. X@item - @var{x}
  1341. XNegation.
  1342. X
  1343. X@item @var{x} * @var{y}
  1344. XMultiplication.
  1345. X
  1346. X@item @var{x} / @var{y}
  1347. XDivision.  Since all numbers in @code{awk} are double-precision
  1348. Xfloating point, the result is not rounded to an integer: @code{3 / 4}
  1349. Xhas the value 0.75.
  1350. X
  1351. X@item @var{x} % @var{y}
  1352. X@c @cindex differences between @code{gawk} and @code{awk}
  1353. XRemainder.  The quotient is rounded toward zero to an integer,
  1354. Xmultiplied by @var{y} and this result is subtracted from @var{x}.
  1355. XThis operation is sometimes known as ``trunc-mod''.  The following
  1356. Xrelation always holds:
  1357. X
  1358. X@example
  1359. Xb * int(a / b) + (a % b) == a
  1360. X@end example
  1361. X
  1362. XOne undesirable effect of this definition of remainder is that
  1363. X@code{@var{x} % @var{y}} is negative if @var{x} is negative.  Thus,
  1364. X
  1365. X@example
  1366. X-17 % 8 = -1
  1367. X@end example
  1368. X
  1369. XIn other @code{awk} implementations, the signedness of the remainder
  1370. Xmay be machine dependent.
  1371. X
  1372. X@item @var{x} ^ @var{y}
  1373. X@itemx @var{x} ** @var{y}
  1374. XExponentiation: @var{x} raised to the @var{y} power.  @code{2 ^ 3} has
  1375. Xthe value 8.  The character sequence @samp{**} is equivalent to
  1376. X@samp{^}.
  1377. X@end table
  1378. X
  1379. X@node Concatenation, Comparison Ops, Arithmetic Ops, Expressions
  1380. X@section String Concatenation
  1381. X
  1382. X@cindex string operators
  1383. X@cindex operators, string
  1384. X@cindex concatenation
  1385. XThere is only one string operation: concatenation.  It does not have a
  1386. Xspecific operator to represent it.  Instead, concatenation is performed by
  1387. Xwriting expressions next to one another, with no operator.  For example:
  1388. X
  1389. X@example
  1390. Xawk '@{ print "Field number one: " $1 @}' BBS-list
  1391. X@end example
  1392. X
  1393. X@noindent
  1394. Xproduces, for the first record in @file{BBS-list}:
  1395. X
  1396. X@example
  1397. XField number one: aardvark
  1398. X@end example
  1399. X
  1400. XWithout the space in the string constant after the @samp{:}, the line
  1401. Xwould run together.  For example:
  1402. X
  1403. X@example
  1404. Xawk '@{ print "Field number one:" $1 @}' BBS-list
  1405. X@end example
  1406. X
  1407. X@noindent
  1408. Xproduces, for the first record in @file{BBS-list}:
  1409. X
  1410. X@example
  1411. XField number one:aardvark
  1412. X@end example
  1413. X
  1414. XSince string concatenation does not have an explicit operator, it is
  1415. END_OF_FILE
  1416.   if test 49625 -ne `wc -c <'./gawk.texinfo.03'`; then
  1417.     echo shar: \"'./gawk.texinfo.03'\" unpacked with wrong size!
  1418.   fi
  1419.   # end of './gawk.texinfo.03'
  1420. fi
  1421. if test -f './missing.d/strchr.c' -a "${1}" != "-c" ; then 
  1422.   echo shar: Will not clobber existing file \"'./missing.d/strchr.c'\"
  1423. else
  1424.   echo shar: Extracting \"'./missing.d/strchr.c'\" \(543 characters\)
  1425.   sed "s/^X//" >'./missing.d/strchr.c' <<'END_OF_FILE'
  1426. X/*
  1427. X * strchr --- search a string for a character
  1428. X *
  1429. X * We supply this routine for those systems that aren't standard yet.
  1430. X */
  1431. X
  1432. Xchar *
  1433. Xstrchr (str, c)
  1434. Xregister char *str, c;
  1435. X{
  1436. X    for (; *str; str++)
  1437. X        if (*str == c)
  1438. X            return str;
  1439. X
  1440. X    return NULL;
  1441. X}
  1442. X
  1443. X/*
  1444. X * strrchr --- find the last occurrence of a character in a string
  1445. X *
  1446. X * We supply this routine for those systems that aren't standard yet.
  1447. X */
  1448. X
  1449. Xchar *
  1450. Xstrrchr (str, c)
  1451. Xregister char *str, c;
  1452. X{
  1453. X    register char *save = NULL;
  1454. X
  1455. X    for (; *str; str++)
  1456. X        if (*str == c)
  1457. X            save = str;
  1458. X
  1459. X    return save;
  1460. X}
  1461. END_OF_FILE
  1462.   if test 543 -ne `wc -c <'./missing.d/strchr.c'`; then
  1463.     echo shar: \"'./missing.d/strchr.c'\" unpacked with wrong size!
  1464.   fi
  1465.   # end of './missing.d/strchr.c'
  1466. fi
  1467. if test -f './version.sh' -a "${1}" != "-c" ; then 
  1468.   echo shar: Will not clobber existing file \"'./version.sh'\"
  1469. else
  1470.   echo shar: Extracting \"'./version.sh'\" \(1509 characters\)
  1471.   sed "s/^X//" >'./version.sh' <<'END_OF_FILE'
  1472. X#! /bin/sh
  1473. X
  1474. X# version.sh --- create version.c
  1475. X
  1476. Xif [ "x$1" = "x" ]
  1477. Xthen
  1478. X    echo you must specify a release number on the command line
  1479. X    exit 1
  1480. Xfi
  1481. X
  1482. XRELEASE="$1"
  1483. X
  1484. Xcat << EOF
  1485. Xchar *version_string = "@(#)Gnu Awk (gawk) ${RELEASE}";
  1486. X
  1487. X/* 1.02        fixed /= += *= etc to return the new Left Hand Side instead
  1488. X        of the Right Hand Side */
  1489. X
  1490. X/* 1.03        Fixed split() to treat strings of space and tab as FS if
  1491. X        the split char is ' '.
  1492. X
  1493. X        Added -v option to print version number
  1494. X         
  1495. X        Fixed bug that caused rounding when printing large numbers  */
  1496. X
  1497. X/* 2.00beta    Incorporated the functionality of the "new" awk as described
  1498. X        the book (reference not handy).  Extensively tested, but no 
  1499. X        doubt still buggy.  Badly needs tuning and cleanup, in
  1500. X        particular in memory management which is currently almost
  1501. X        non-existent. */
  1502. X
  1503. X/* 2.01        JF:  Modified to compile under GCC, and fixed a few
  1504. X        bugs while I was at it.  I hope I didn't add any more.
  1505. X        I modified parse.y to reduce the number of reduce/reduce
  1506. X        conflicts.  There are still a few left. */
  1507. X
  1508. X/* 2.02        Fixed JF's bugs; improved memory management, still needs
  1509. X        lots of work. */
  1510. X
  1511. X/* 2.10        Major grammar rework and lots of bug fixes from David.
  1512. X        Major changes for performance enhancements from David.
  1513. X        A number of minor bug fixes and new features from Arnold.
  1514. X        Changes for MSDOS from Conrad Kwok and Scott Garfinkle.
  1515. X        The gawk.texinfo and info files included! */
  1516. X
  1517. X/* 2.11        Bug fix release to 2.10.  Lots of changes for portability,
  1518. X        speed, and configurability.  */
  1519. XEOF
  1520. Xexit 0
  1521. END_OF_FILE
  1522.   if test 1509 -ne `wc -c <'./version.sh'`; then
  1523.     echo shar: \"'./version.sh'\" unpacked with wrong size!
  1524.   fi
  1525.   # end of './version.sh'
  1526. fi
  1527. echo shar: End of archive 6 \(of 16\).
  1528. cp /dev/null ark6isdone
  1529. MISSING=""
  1530. for I in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ; do
  1531.     if test ! -f ark${I}isdone ; then
  1532.     MISSING="${MISSING} ${I}"
  1533.     fi
  1534. done
  1535. if test "${MISSING}" = "" ; then
  1536.     echo You have unpacked all 16 archives.
  1537.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1538. else
  1539.     echo You still must unpack the following archives:
  1540.     echo "        " ${MISSING}
  1541. fi
  1542. exit 0
  1543. exit 0 # Just in case...
  1544.